package meijuli.com.join51.business.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.jhx.common.utils.Constants;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.aliyun.AliyunOSS;

import com.nostra13.universalimageloader.cache.disc.impl.BaseDiskCache;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.process.BitmapProcessor;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 作者: Ryan
 * 创建时间:15/1/28 11:42
 * 类描述:Android-Universal-PictureLoader 工具类
 * <p/>
 * Android-Universal-Image-Loader 支持的Uri 类型
 * "http://site.com/image.png" // from Web
 * "file:///mnt/sdcard/image.png" // from SD card
 * "file:///mnt/sdcard/video.mp4" // from SD card (video thumbnail)
 * "content://media/external/images/media/13" // from content provider
 * "content://media/external/video/media/13" // from content provider (video thumbnail)
 * "assets://image.png" // from assets
 * "drawable://" + R.drawable.img // from drawables (non-9patch images)
 */
public class UniversualImageLoaderUtils {

    private static final String TAG = "UniversualImageLoaderUtils";
    private static BaseImageDownloader baseImageDownloader;

    public static final void initImageLoader(Context context) {
        File cacheDir = StorageUtils.getOwnCacheDirectory(context, context.getPackageName() + "/imgs");
        BaseDiskCache baseDiscCache = new UnlimitedDiskCache(cacheDir);
        baseImageDownloader = new BaseImageDownloader(context);
        ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().diskCacheFileNameGenerator(new Md5FileNameGenerator()).diskCacheSize(50 * 1024 * 1024) // 50 Mb
                .tasksProcessingOrder(QueueProcessingType.LIFO).diskCache(baseDiscCache).imageDownloader(baseImageDownloader);// Remove for release app
        if (Constants.PRINT_LOG) {
            //            builder.writeDebugLogs();
        }
        ImageLoaderConfiguration config = builder.build();
        ImageLoader.getInstance().init(config);
    }

    public static BaseImageDownloader getBaseImageDownloader() {
        return baseImageDownloader;
    }

    public static DisplayImageOptions getDisplayImageOptions() {
        return new DisplayImageOptions.Builder().showImageForEmptyUri(R.mipmap.img_default).showImageOnLoading(R.mipmap.img_default).showImageOnFail(R.mipmap.img_default).considerExifParams(false).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
    }

    public static DisplayImageOptions getDisplayImageOptions(boolean considerExifParams) {
        return new DisplayImageOptions.Builder().considerExifParams(considerExifParams).cacheInMemory(false).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).build();
    }

    public static DisplayImageOptions getDisplayImageOptions(final ImageSize targetImageSize) {
        return new DisplayImageOptions.Builder().showImageForEmptyUri(R.mipmap.img_default).showImageOnLoading(R.mipmap.img_default).showImageOnFail(R.mipmap.img_default).considerExifParams(false).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).postProcessor(new BitmapProcessor() {
            @Override
            public Bitmap process(Bitmap bitmap) {
                return Bitmap.createScaledBitmap(bitmap, targetImageSize.getWidth(), targetImageSize.getHeight(), false);
            }
        }).build();
    }

    public static DisplayImageOptions getRoundCornerImageOptions(final ImageSize targetImageSize, int dpCorners) {
        return new DisplayImageOptions.Builder().showImageForEmptyUri(R.mipmap.img_default).showImageOnLoading(R.mipmap.img_default).showImageOnFail(R.mipmap.img_default).considerExifParams(false).cacheInMemory(true).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).postProcessor(new BitmapProcessor() {
            @Override
            public Bitmap process(Bitmap bitmap) {
                return Bitmap.createScaledBitmap(bitmap, targetImageSize.getWidth(), targetImageSize.getHeight(), false);
            }
        }).displayer(new RoundedBitmapDisplayer(DensityUtil.dip2px(dpCorners), 0)).build();
    }

    public static DisplayImageOptions getRoundCornerImageOptions(int dpCorners) {
        return new DisplayImageOptions.Builder().showImageForEmptyUri(R.mipmap.img_default).showImageOnLoading(R.mipmap.img_default).showImageOnFail(R.mipmap.img_default).showImageForEmptyUri(R.mipmap.img_default).showImageOnLoading(R.mipmap.img_default).showImageOnFail(R.mipmap.img_default).considerExifParams(false).cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565).cacheOnDisk(true).displayer(new RoundedBitmapDisplayer(DensityUtil.dip2px(dpCorners), 0)).build();
    }

    public static DisplayImageOptions getTopRoundCornerImageOptions(int dpCorners) {
        return new DisplayImageOptions.Builder().showImageForEmptyUri(R.mipmap.img_default).showImageOnLoading(R.mipmap.img_default).showImageOnFail(R.mipmap.img_default).showImageForEmptyUri(R.mipmap.img_default).showImageOnLoading(R.mipmap.img_default).showImageOnFail(R.mipmap.img_default).considerExifParams(false).cacheInMemory(true).bitmapConfig(Bitmap.Config.RGB_565).cacheOnDisk(true).displayer(new TopRoundedBitmapDisplayer(DensityUtil.dip2px(dpCorners), 0)).build();
    }

    /**
     * 获取本地资源图片的Uri地址 Android-Universal-Image-Loader支持
     *
     * @param resID
     * @return
     */
    public static String generateLocalResImgUri(int resID) {
        return "drawable://" + resID;
    }

    public static String generateAssetsImgUri(String assetFileName) {
        return "assets://" + assetFileName;
    }

    /**
     * 下载显示阿里云图片
     *
     * @param bucketName          图片所在的桶名
     * @param cloudKey            文件名
     * @param imageView           显示图片的ImageView
     * @param displayImageOptions 显示图片的配置信息
     * @param listener            图片加载监听器
     */
    public static void displayAliyunImage(String bucketName, String cloudKey, ImageView imageView, DisplayImageOptions displayImageOptions, ImageLoadingListener listener) {
        String url = AliyunOSS.get().getAliyunImageUrl(bucketName, cloudKey);
        if (!StringUtil.isEmpty(url)) {
            ImageLoader.getInstance().displayImage(url, imageView, displayImageOptions, listener);
        } else {
//            LogUtils.e(TAG, " 非法的图片下载地址: bucketName = " + bucketName + " ; cloudKey = " + cloudKey);
        }
    }

    /**
     * 下载显示阿里云图片
     *
     * @param bucketName          图片所在的桶名
     * @param cloudKey            文件名
     * @param imageView           显示图片的ImageView
     * @param displayImageOptions 显示图片的配置信息
     * @param listener            图片加载监听器
     */
    public static void displayAliyunImage(String bucketName, String cloudKey, ImageView imageView, DisplayImageOptions displayImageOptions, ImageLoadingListener listener, ImageLoadingProgressListener imageLoadingProgressListener) {
        String url = AliyunOSS.get().getAliyunImageUrl(bucketName, cloudKey);
        ImageLoader.getInstance().displayImage(url, imageView, displayImageOptions, listener, imageLoadingProgressListener);
    }

    public static class AliyunImageDownloader extends BaseImageDownloader {

        public AliyunImageDownloader(Context context) {
            super(context);
        }

        public AliyunImageDownloader(Context context, int connectTimeout, int readTimeout) {
            super(context, connectTimeout, readTimeout);
        }

        @Override
        public InputStream getStream(String imageUri, Object extra) throws IOException {

//            if (imageUri.startsWith("http://www.aimianfei.com/")) {
//                String bucketAndKey = imageUri.substring(imageUri.indexOf("http://www.aimianfei.com/"));
//                String[] bucketKey = bucketAndKey.split("_B_U_C_K_E_T_AND_K_E_Y_");
//                String bucketName = bucketKey[0];
//                String cloudKey = bucketKey[1];
//                //                try {
//                //                    return AliyunOSS.get().downloadDataFromOSS(bucketName, cloudKey);
//                //                } catch (OSSException e) {
//                //                    e.printStackTrace();
//                //                }
//            }
            return super.getStream(imageUri, extra);
        }
    }
}